<template>
    <div class="base-page">
        <div class="left org">
            <select-org @select="onSelectOrg" />
        </div>
        <!-- 列表 -->
        <div class="right" v-show="viewList === true">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="primary"
                                @click="onDistRole"
                                :disabled="!currentRow"
                                class="btn-greenYellow"
                            >分配角色</el-button>
                            <span class="prompt" v-if="!currentRow">请先选择用户</span>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <!-- <div class="adverse">
                            <el-button type="primary" @click="onAdvanceSearch">高级搜索</el-button>
                        </div> -->
                    </div>
                </div>
            </div>
            <div class="e-table" :style="{width: rightTableWidth}">
                <el-table
                    class="table"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    :cell-class-name="cellClsNm"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                    ref="tableRef"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                >
                    <el-table-column label="序号" type="index" width="55"> </el-table-column>
                    <el-table-column prop="userName" label="用户名称" width="200"> </el-table-column>
                    <el-table-column prop="orgName" label="所属机构" min-width="200" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="jobName" label="岗位名称" width="200" show-overflow-tooltip> </el-table-column>
                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="getTableData"
                @sizeChange="getTableData"
            />
        </div>
        <!-- 分配角色界面 -->
        <div class="right" v-if="viewList === 'role'">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button
                                key="return"
                                icon="el-icon-d-arrow-left"
                                @click="goList"
                            >返回列表</el-button>
                            <el-button type="primary"
                                @click="onSelectRole"
                                class="btn-greenYellow"
                            >选择角色</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="e-form" style="padding: 0 10px 10px;">
                <div class="tabs-title">已分配角色</div>
                <el-table
                    :style="{width: rightTableWidth2}"
                    :height="rightTableHeight2"
                    class="table e-table"
                    :data="tableData2"
                    border
                    :cell-class-name="cellClsNm"
                    ref="tableRef2"
                    v-sortTable="{ 'tableData': tableData2, '_this': this, 'ref': 'tableRef2' }"
                >
                    <el-table-column label="序号" type="index" width="55"></el-table-column>
                    <el-table-column label="操作" width="120">
                        <template slot-scope="scoce">
                            <i class="el-icon-delete"
                                @click="onDel(scoce.$index)"
                                title="删除"
                            ></i>
                        </template>
                    </el-table-column>
                    <el-table-column prop="roleName" label="角色名称">
                        <template slot-scope="{ row }">
                            <span>{{ row.roleName || '无'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="orgName" label="所属机构"> </el-table-column>
                </el-table>
            </div>

            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary"
                        @click="onSave"
                    >保存</el-button>
                    <el-button
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import SelectOrg from '@/components/selectOrg'
import Pagination from '@/components/pagination/pagination'
// eslint-disable-next-line no-unused-vars
import { getUserUnderOrgApi, saveOrgRoleApi, getRoleByOrg } from '@/api/base/system'
// eslint-disable-next-line no-unused-vars
import { debounce, advanceSearch, showLoading, hideLoading, selectDataClient, openAppClient } from '@/utils/common'
import { mapState } from 'vuex'
export default {
    components: {
        Pagination,
        SelectOrg
    },
    computed: {
        ...mapState(['userInfo']),
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 416) + 'px'
        },
        // 列表高度
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 416) + 'px'
        },
        rightTableHeight2 () {
            return this.screenHeight - 210
        }
    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            treeData: [],
            currentRow: null,
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            tableData: [],
            allData: [],
            formData: {},
            currencyOptions: [],
            tabsName: 'baseInfo',
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: []
        }
    },
    mounted () {
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        async getTableData () {
            showLoading()
            try {
                const { orgId } = this.formData
                const resData = await getUserUnderOrgApi({
                    orgId,
                    keyWord: this.searchKey,
                    limit: this.paginationInfo.pageSize,
                    page: this.paginationInfo.currentPage
                })
                this.tableData = resData.list
                this.allData = JSON.parse(JSON.stringify(resData.list))
                this.paginationInfo.total = resData.totalCount
                this.viewList = true
                hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        async queryTableData () {
            const resData = this.allData.filter(item => {
                return item.userName.includes(this.searchKey)
            })
            this.tableData = resData
            this.paginationInfo.total = 0
        },
        onSelectOrg (val) {
            this.formData = {
                ...val
            }
            this.onSearch('')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            this.paginationInfo.pageSize = 20
            this.paginationInfo.currentPage = 1
            this.searchKey = searchKey
            this.getTableData()
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        goList () {
            this.viewList = true
        },
        handleCurrentChange (val) {
            console.log('handleCurrentChange: ', val)
            this.currentRow = val
        },
        // 点击分配角色按钮
        async onDistRole () {
            this.viewList = 'role'
            const data = await getRoleByOrg({
                orgId: this.currentRow.orgId,
                userId: this.currentRow.userId
            })
            this.tableData2 = data.filter(item => item.userId)
        },
        // 选择角色
        onSelectRole () {
            const SelectedIDs = this.tableData2.map(item => item.roleId)
            selectDataClient({
                SelectServiceToken: '/hr/role/getOrgRole', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs, // 已选中id
                InitParamsStr: JSON.stringify({
                    orgId: this.currentRow.orgId,
                    userId: ''
                }),
                Title: '选择角色' // 标题
            }).then(val => {
                val.forEach(item => {
                    item.userId = this.currentRow.userId
                    item.userName = this.currentRow.userName
                })
                // 保存用户选择返回数据到store
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果')
                this.tableData2 = val
            })
        },
        // 保存分配角色
        async onSave () {
            showLoading()
            try {
                await saveOrgRoleApi({
                    url: {
                        orgId: this.currentRow.orgId,
                        userId: this.currentRow.userId,
                    },
                    params: this.tableData2
                })
                hideLoading()
                this.clientPop('suc', '保存成功', () => {
                    this.getTableData()
                })
            } catch (error) {
                hideLoading()
            }
            this.viewList = true
        },
        onDel (index) {
            this.tableData2.splice(index, 1)
        },
        onCancel () {
            this.viewList = true
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
    }
}
</script>

<style lang="scss" scoped>
</style>
